<template>
    <div class="update-photo">
        <img class="img" :src="img" alt="" ref="img">

        <div class="toolbar">
            <div class="cancel" @click="$emit('close')">取消</div>
            <div class="confirm" @click="onConfirm">完成</div>
        </div>
    </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'

export default {
    name: 'UpdatePhoto',
    props: ['img'],
    data () {
        return {
            cropper: null
        }
    },
    methods: {
        onConfirm () {
            console.log(this.cropper.getData()) // 服务端裁切需要传递的参数

            try {
                // 客户端裁切
                this.cropper.getCroppedCanvas().toBlob(async blob => {
                    // 如果接口要求Content-Type 是 application/json
                    // 可传递js对象
                    // updateUserPhoto({
                    //     photo: blob
                    // })

                    // 如果接口要求的Content-Type 是 multipart/form-data
                    // 则必须传递FormData对象
                    const formData = new FormData()
                    formData.append('photo', blob)
                    const res = await updateUserPhoto(formData)
                    console.log(res)

                    this.$emit('close')
                    this.$emit('updatePhoto', res.data.data.photo)
                    this.$toast.success('更新成功')
                })
            } catch (error) {
                this.$toast.fail('更新失败')
            }
        }
    },
    mounted () {
        const image = this.$refs.img
        this.cropper = new Cropper(image, {
            viewMode: 1, // 只能在裁剪的图片范围内移动
            dragMode: 'move', // 画布和图片都可以移动
            aspectRatio: 1, // 裁剪区默认正方形
            autoCropArea: 1, // 自动调整裁剪图片
            cropBoxMovable: false, // 禁止裁剪区移动
            cropBoxResizable: false, // 禁止裁剪区缩放
            background: false // 关闭默认背景
        })
    }
}
</script>

<style scoped lang="less">
.update-photo {
    background-color: #333;
    height: 100%;
    .img {
        display: block;
        width: 100%;
    }
    .toolbar {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        justify-content: space-between;
        .cancel,
        .confirm {
            width: 90px;
            height: 90px;
            font-size: 30px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
        }
    }
}
</style>
